package cn.le.util;

import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

public class WebSocketUtil {

    private static final Map<String, CopyOnWriteArrayList<WebSocketSession>> SESSION_MAP = new HashMap<>();


    public static void put(String did,WebSocketSession session){
        CopyOnWriteArrayList<WebSocketSession> list = SESSION_MAP.get(did);
        if (list == null){
            list = new CopyOnWriteArrayList();
            SESSION_MAP.put(did,list);
        }
        list.add(session);
    }

    public static void remove(String did,WebSocketSession session){
        CopyOnWriteArrayList<WebSocketSession> list = SESSION_MAP.get(did);
        if (CollectionUtils.isEmpty(list)){
            return;
        }

        int index = -1;
        Iterator<WebSocketSession> it = list.iterator();
        while (it.hasNext()){
            index++;
            WebSocketSession se = it.next();
            if (se == session){
                list.remove(index);
                return;
            }
        }
        if (CollectionUtils.isEmpty(list)){
            SESSION_MAP.remove(did);
        }
    }

    public static boolean isEmpty(){
        return SESSION_MAP.size() > 0 ? false : true;
    }

    public static CopyOnWriteArrayList<WebSocketSession> findSocketConnect(String did){
        return SESSION_MAP.get(did);
    }
}
